
#include <boost/filesystem.hpp>
#include "loghelper.h"
#include "tcpserver_impl.h"
#include "tcpserver_session.h"
#include "messagehandler.h"

using namespace boost;
using boost::asio::ip::tcp;
using namespace RockLog;

TcpServerImpl::TcpServerImpl(boost::asio::io_context& io_context,
    const tcp::endpoint& listen_endpoint, MessageType_t &messageTypes, ServerConfig_t& cfg, MessageHandlerBase* messageHandler)
    : _io_context(io_context),
    _acceptor(io_context, listen_endpoint),
    _messageTypes(messageTypes),
    _cfg(cfg),
    _messageHandler(messageHandler)
{
    startAccept();
}

TcpServerImpl::~TcpServerImpl()
{
}

void TcpServerImpl::startAccept()
{
    TcpServerSessionPtr new_session(new TcpServerSession(_io_context, _sessions, _messageTypes, _cfg));

    _acceptor.async_accept(new_session->socket(),
        std::bind(&TcpServerImpl::handleAccept, this, new_session, std::placeholders::_1));

    new_session->recvTcpMessageSignal.connect(std::bind(&MessageHandlerBase::readBody, _messageHandler, std::placeholders::_1));
    _messageHandler->sendTcpMessageSignal.connect(std::bind(&TcpServerSession::writeTcpSessionMessage, new_session, std::placeholders::_1));
}

void TcpServerImpl::handleAccept(TcpServerSessionPtr session, const boost::system::error_code& ec)
{
    if (!ec)
    {
        session->start();
    }

    //startAccept();
}

